#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/9/24 17:09
# @Author    :cjw
from typing import List

from fastapi import APIRouter, Depends
from loguru import logger
from sqlalchemy.orm import Session

from app.api.utils.dependencies import get_db
from app.crud import task as task_crud
from app.schemas.msg import Msg
from app.utils.execute_tools import ExecuteTools
from app.schemas.case import Case
from app.schemas.task import TaskCreate

router = APIRouter(prefix='/task', tags=['任务管理'])


@router.get('/page_size', response_model=Msg, summary='分页获取任务信息')
def get_tasks(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    """

    :param skip:
    :param limit:
    :param db:
    :return:
    """
    task_data = task_crud.get_tasks(db, skip, limit)
    count = task_crud.get_task_count(db)
    msg = {'code': 0, 'data': task_data, 'count': count.get('count', 0), 'msg': '获取成功'}
    logger.info(msg)
    return msg


@router.post('/create', response_model=Msg, summary='新增任务信息')
def create_task(case: List[Case], db: Session = Depends(get_db)):
    """
    1、调用jenkins执行用例
    2、执行用例之后，写入执行记录到数据库
    :return:
    """
    # 执行指定的任务
    node_ids = [c.node_id for c in case]
    node_id = ' '.join(node_ids)
    execute = ExecuteTools('http://101.34.44.7:8080/', 'cjw', '1128e80f11866f94ecb7cf0fa7ec6cddb9')
    allure_url = execute.invoke('pt_test', {'task': node_id})

    # 获取数据构建任务数据，进行持久化
    task = TaskCreate(information=node_id, report=allure_url)
    try:
        task_crud.create_task(db, task)
        logger.info(f'执行结果的allure报告地址：{allure_url}')
        msg = {'code': 0, 'data': task.dict(), 'msg': '创建成功'}
        logger.info(msg)
        return msg
    except Exception as e:
        msg = {'code': -1, 'data': task.dict(), 'msg': '创建失败'}
        logger.info(msg)
        logger.info(f'创建失败原因：{e}')
        return msg
